import Vue from 'vue'
import Vuex from 'vuex'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { $get } from "@/utils/api.js";

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
  state: {
    sessions: [],
    users: [],
    currentSessionId: 1,
    filterKey: '',
    stomp: null
  },
  mutations: {
    changeCurrentSessionId(state, id) {
      state.currentSessionId = id;
    },
    addMessage(state, msg) {
      state.sessions[state.currentSessionId - 1].messages.push({
        content: msg,
        date: new Date(),
        self: true
      })
    },
    INIT_DATA(state) {
      let data = localStorage.getItem('vue-chat-session');
      //console.log(data)
      if (data) {
        state.sessions = JSON.parse(data);
      }
    },
    INIT_USERS(state, data) {
      state.users = data
    }
  },
  actions: {
    connect(context) {
      context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
      let token = window.sessionStorage.getItem('tokenStr');
      context.state.stomp.connect({ 'Auth-Token': token }, success => {
        context.state.stomp.subscribe('/user/queue/chat', msg => {
          console.log(msg.body);
        })
      }, error => {
        console.log(error);
      })
    },
    initData(context) {
      $get('/user/' + this.currentSessionId).then((res) => {
        if (res) {
          context.commit('INIT_USERS', res)
        }
      })
    },
  },

})

store.watch(function (state) {
  return state.sessions
}, function (val) {
  console.log('CHANGE: ', val);
  localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
  deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})

export default store;